#!/bin/bash

MAXLOADMINI=10
MAXLOADMEDIUM=25
CMD="qemu-system-x86_64"
MEMSMINI=54
MEMSMEDIUM=212

case $1 in 
	status )
			case $2 in
				html )
					if ps -p $(cat svmm_db/pids/$3.pid) > /dev/null 
					then
						echo "<div style='display:inline;color:#00ff00;'>Running</div>"
					else
						echo "<div style='display:inline;color:#ff0000;'>Stopped</div>"
					fi
				;;
				
				return )
					if ps -p $(cat svmm_db/pids/$3.pid) > /dev/null 
					then
						echo "1"
					else
						echo "0"
					fi
				;;
			esac
			;;
	start-mini )
		$CMD -enable-kvm -daemonize -display none -smp 1 -hda svmm_db/disks/$2.img -m ${MEMSMINI}M -net nic,model=pcnet -net user,hostfwd=tcp::${2}80-:80,hostfwd=tcp::${2}22-:22,hostfwd=tcp::${2}66-:6666,hostfwd=tcp::${2}21-:21,hostfwd=tcp::${2}67-:6667 -pidfile svmm_db/pids/$2.pid
		
		sleep 10

		./setcpulimit $(cat svmm_db/pids/$2.pid) $MAXLOADMINI > /dev/null &

		#./setkilltimer $(cat svmm_db/pids/$2.pid) $2 > /dev/null &
		;;

	start-medium )
        $CMD -enable-kvm -daemonize -display none -smp 1 -hda svmm_db/disks/$2.img -m ${MEMSMEDIUM}M -net nic,model=pcnet -net user,hostfwd=tcp::${2}80-:80,hostfwd=tcp::${2}22-:22,hostfwd=tcp::${2}66-:6666,hostfwd=tcp::${2}65-:25665,hostfwd=tcp::${2}21-:21,hostfwd=tcp::${2}67-:6667 -pidfile svmm_db/pids/$2.pid

        sleep 20

        ./setcpulimit $(cat svmm_db/pids/$2.pid) $MAXLOADMEDIUM > /dev/null &

        #./setkilltimer $(cat svmm_db/pids/$2.pid) $2 > /dev/null &
        ;;

	stopall )
        killall $CMD
        ;;

	stop ) 
        kill -TERM $(cat svmm_db/pids/$2.pid)
        ;;
	del )
        kill -TERM $(cat svmm_db/pids/$2.pid)
        rm svmm_db/disks/$2.img
        rm svmm_db/pids/$2.pid
		;;
	* )
 		echo "Usage: machine {start-mini|start-large|status|stop|stopall} {_|html|return} [vm id]";;
esac
